package com.lanxin.xx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanxin.hr.entity.ZzAccount;
import com.lanxin.hr.entity.ZzEmployee;
import com.lanxin.hr.service.IZzEmployeeService;
import com.lanxin.xx.entity.XxInformation;
import com.lanxin.xx.service.IXxInformationService;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器（仅接收参数并传递给Service）
 * </p>
 *
 * @author zyq
 * @since 2025-07-26
 */
@Controller
@RequestMapping("/xx/information")
public class XxInformationController {

    private static final Logger logger = Logger.getLogger(XxInformationController.class);

    @Autowired
    private IXxInformationService xxInformationService;

    @Autowired
    private IZzEmployeeService employeeService;

    /**
     * 列表所有发布的信息
     */
    @RequestMapping("/listInformation")
    public String listInformation(Model model,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "5") Integer pageSize,
                                  HttpServletRequest request) {

        Page<XxInformation> pageParam = new Page<>(page, pageSize);

        // 获取搜索参数
        String typeid = request.getParameter("typeid");
        String title = request.getParameter("title");
        String creator = request.getParameter("creator");
        String publishDate = request.getParameter("publishDate");

        // 构建查询条件
        QueryWrapper<XxInformation> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(typeid)) {
            queryWrapper.eq("typeid", Integer.valueOf(typeid)); // 转换为Integer
        }
        if (StringUtils.hasText(title)) {
            queryWrapper.like("title", title);
        }
        if (StringUtils.hasText(creator)) {
            queryWrapper.eq("creator", creator);
        }
        if (StringUtils.hasText(publishDate)) {
            LocalDateTime start = LocalDate.parse(publishDate).atStartOfDay();
            LocalDateTime end = LocalDate.parse(publishDate).atTime(23, 59, 59, 999_000_000);
            queryWrapper.between("publish_date", start, end);
        }

        List<ZzEmployee> employees = employeeService.list();

        // 执行分页查询
        IPage<XxInformation> pageInfo = xxInformationService.page(pageParam, queryWrapper);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("searchTypeid", typeid);
        model.addAttribute("employees", employees);
        model.addAttribute("searchTitle", title);
        model.addAttribute("searchCreator", creator);
        model.addAttribute("searchPublishDate", publishDate);

        return "xx/listInformation";
    }


    /**
     * 首页展示最新公告信息（公司新闻、通知公告）
     */
    @RequestMapping("/listInformationToHome")
    public String listInformationToHome(Model model) {
        // 1. 查询最新的公司新闻（假设类型ID为1，取前5条）
        QueryWrapper<XxInformation> newsQuery = new QueryWrapper<>();
        newsQuery.eq("typeid", 1) // 类型ID：1=公司新闻
                .orderByDesc("publishDate") // 按发布时间倒序
                .last("limit 5"); // 只取前5条
        List<XxInformation> newsList = xxInformationService.list(newsQuery);

        // 2. 查询最新的通知公告（假设类型ID为2，取前5条）
        QueryWrapper<XxInformation> noticeQuery = new QueryWrapper<>();
        noticeQuery.eq("typeid", 2) // 类型ID：2=通知公告
                .orderByDesc("publishDate")
                .last("limit 5");
        List<XxInformation> noticeList = xxInformationService.list(noticeQuery);

        // 3. 将数据传递到前端页面
        model.addAttribute("newsList", newsList); // 公司新闻列表
        model.addAttribute("noticeList", noticeList); // 通知公告列表

        // 4. 返回首页视图
        return "home";
    }


    /**
     * 去发布页面
     */
    @RequestMapping("/toAddInformation")
    public String toAddInformation(Model model) {
        return "xx/AddInformation";
    }


    /**
     * 发布信息（接收参数并传递给Service处理）
     */
    @PostMapping("/addInformation")
    public String addInformation(XxInformation xxInformation,
                                 @RequestParam(value = "accpath", required = false) MultipartFile file,
                                 Model model,
                                 HttpServletRequest request,
                                 HttpSession session) {
        try {
            // 从session获取当前登录用户ID并设置到实体
            xxInformation.setCreator((Integer) session.getAttribute("loginUserId"));
            // 调用Service处理添加逻辑（包含文件上传）
            boolean result = xxInformationService.addInformation(xxInformation, file, request);

            if (result) {
                logger.info("发布信息成功：" + xxInformation.getTitle());
            } else {
                logger.error("发布信息失败：" + xxInformation.getTitle());
                model.addAttribute("errorMsg", "发布失败，请重试");
                return "xx/AddInformation";
            }
        } catch (Exception e) {
            logger.error("发布信息异常", e);
            model.addAttribute("errorMsg", "发布失败：" + e.getMessage());
            return "xx/AddInformation";
        }
        return "redirect:/xx/information/listInformation";
    }

    /**
     * 去修改页面
     */
    @RequestMapping("/toUpdateInformation")
    public String toUpdateInformation(Model model, Integer oid) {
        XxInformation xxInformation = xxInformationService.getById(oid);
        model.addAttribute("xxInformation", xxInformation);
        return "xx/UpdateInformation";
    }

    /**
     * 修改信息（接收参数并传递给Service处理）
     */
    @RequestMapping("/editInformation")
    public String editInformation(XxInformation xxInformation,
                                  @RequestParam(value = "accpath", required = false) MultipartFile file,
                                  Model model,
                                  HttpServletRequest request) {
        try {
            // 调用Service处理更新逻辑（包含文件上传）
            boolean result = xxInformationService.updateInformation(xxInformation, file, request);

            if (result) {
                logger.info("更新信息成功：" + xxInformation.getOid());
            } else {
                logger.error("更新信息失败：" + xxInformation.getOid());
                model.addAttribute("errorMsg", "更新失败，请重试");
                return "xx/UpdateInformation";
            }
        } catch (Exception e) {
            logger.error("更新信息异常", e);
            model.addAttribute("errorMsg", "更新失败：" + e.getMessage());
            return "xx/UpdateInformation";
        }
        return "redirect:/xx/information/listInformation";
    }

    /**
     * 删除信息
     */
    @RequestMapping("/deleteInformal")
    public String deleteInformal(Integer oid) {
        if (oid == null) {
            logger.error("删除信息失败：oid为空");
            return "redirect:/xx/information/listInformation";
        }
        boolean result = xxInformationService.removeById(oid);
        logger.info("删除信息结果：" + (result ? "成功" : "失败") + "，oid=" + oid);
        return "redirect:/xx/information/listInformation";
    }

    /**
     * 详情页面
     */
    @RequestMapping("/informationInfo")
    public String informationInfo(Model model, Integer oid) {
        XxInformation info = xxInformationService.getById(oid);
        List<ZzEmployee> employees = employeeService.list();
        model.addAttribute("employees", employees);
        model.addAttribute("info", info);
        return "xx/informationInfo";
    }

    /**
     * 附件下载（
     */
    @RequestMapping("/downloadInfoFile")
    public void downloadInfoFile(
            Integer oid,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws IOException {
        // 1. 校验参数
        if (oid == null) {
            logger.error("下载失败：信息ID（oid）为空");
            return;
        }

        // 2. 获取信息记录
        XxInformation info = xxInformationService.getById(oid);
        if (info == null || StringUtils.isEmpty(info.getFile())) {
            logger.error("下载失败：信息不存在或无附件，oid=" + oid);
            return;
        }

        // 3. 构建文件路径
        String fileRelativePath = info.getFile(); // 格式：upload/xx/1690000000_xxx.pdf
        String filePath = request.getServletContext().getRealPath("/WEB-INF/static/" + fileRelativePath);
        File file = new File(filePath);

        // 4. 校验文件存在
        if (!file.exists() || !file.isFile()) {
            logger.error("下载失败：文件不存在，路径=" + filePath);
            return;
        }

        // 5. 提取文件名
        int lastSlashIndex = fileRelativePath.lastIndexOf("/");
        String fileName = fileRelativePath.substring(lastSlashIndex + 1); // 提取：1690000000_xxx.pdf

        // 6. 编码文件名
        fileName = URLEncoder.encode(fileName, "UTF-8");

        // 7. 设置响应头
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentLength((int) file.length());

        // 8. 复制文件流
        try {
            FileUtils.copyFile(file, response.getOutputStream());
        } catch (IOException e) {
            logger.error("文件复制失败");
        }
    }
}
